<script setup>
import { ref, onMounted, computed, onUnmounted } from 'vue'
import { shopItemService } from '@/services/shop_item'
import { userManager } from '@/utils/user'
import { imagePath } from '@/utils/image'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Clock, Picture, Ticket, CircleCheck, Checked, CircleCheckFilled, Loading } from '@element-plus/icons-vue'

// 商品类型枚举
const ITEM_TYPE = {
  VIRTUAL: 0, // 虚拟卡
  PHYSICAL: 1, // 实体商品
  FRAME: 2    // 头像框
}

// 购物记录数据
const shopHistory = ref([])
const isLoading = ref(true)
const errorMessage = ref('')
const countdownTimers = ref({})
const activeTab = ref('virtual') // 默认显示虚拟卡

// 有效期配置
const validityPeriod = [
  { item_id: '0063ad4f-d040-48c1-b3ca-bc1f338c1796', period: 7 },
  { item_id: '00670f04-5051-4aaa-a165-091ead954d09', period: 14 },
  { item_id: '0073d15b-8263-49a8-8ede-201fba7dff57', period: 1 },
  { item_id: '01e609cb-0f47-4982-9f5b-5236c46d2ec0', period: 30 },
  { item_id: '00991174-410c-4570-ba26-2035e56247d5', period: 1 },
  { item_id: '0099bdd7-5c50-4f2a-8207-01c2c77802dd', period: 1 }
]

// 过滤后的购物记录
const filteredHistory = computed(() => {
  if (activeTab.value === 'virtual') {
    // 对于虚拟卡，合并相同类型的未使用卡片
    const virtualItems = shopHistory.value.filter(item => item.type === ITEM_TYPE.VIRTUAL)
    const groupedItems = {}
    
    virtualItems.forEach(item => {
      if (item.isEffective) {
        // 未使用的卡片，按类型分组
        if (!groupedItems[item.item_id]) {
          groupedItems[item.item_id] = {
            ...item,
            count: 1,
            isGrouped: true
          }
        } else {
          groupedItems[item.item_id].count++
        }
      } else {
        // 已使用的卡片单独显示
        groupedItems[item.item_id + '_' + item.date] = {
          ...item,
          count: 1,
          isGrouped: false
        }
      }
    })
    
    return Object.values(groupedItems)
  } else if (activeTab.value === 'physical') {
    return shopHistory.value.filter(item => item.type === ITEM_TYPE.PHYSICAL)
  } else if (activeTab.value === 'frame') {
    return shopHistory.value.filter(item => item.type === ITEM_TYPE.FRAME)
  }
  return shopHistory.value
})

// 计算剩余时间
const calculateRemainingTime = (item_id, endDate) => {
  const validityItem = validityPeriod.find(v => v.item_id === item_id)
  const periodDays = validityItem ? validityItem.period : 7
  
  const now = new Date()
  const end = new Date(endDate)
  const diff = end - now + periodDays * 24 * 60 * 60 * 1000

  if (diff <= 0) {
    return { 
      days: 0, 
      hours: 0, 
      minutes: 0, 
      seconds: 0, 
      expired: true,
      period: periodDays
    }
  }
  
  const days = Math.floor(diff / (1000 * 60 * 60 * 24))
  const hours = Math.floor((diff % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60))
  const minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60))
  const seconds = Math.floor((diff % (1000 * 60)) / 1000)
  
  return { 
    days, 
    hours, 
    minutes, 
    seconds, 
    expired: false,
    period: periodDays
  }
}

// 初始化倒计时
const initCountdowns = () => {
  shopHistory.value.forEach(item => {
    if (item.type === ITEM_TYPE.VIRTUAL && !item.isEffective && item.date) {
      const remaining = calculateRemainingTime(item.item_id, item.date)
      if (!remaining.expired) {
        updateCountdown(item.item_id, item.date)
        countdownTimers.value[item.item_id] = setInterval(() => {
          updateCountdown(item.item_id, item.date)
        }, 1000)
      }
    }
  })
}

// 检查同一种卡今天是否已使用
const hasUsedSameCardToday = computed(() => {
  const today = new Date().toDateString()
  return (itemId) => {
    return shopHistory.value.some(item => 
      item.item_id === itemId && 
      !item.isEffective && 
      new Date(item.date).toDateString() === today
    )
  }
})

// 更新倒计时显示
const updateCountdown = (itemId, date) => {
  const item = shopHistory.value.find(i => i.item_id === itemId && i.date === date)
  if (!item || !item.date) return
  
  const remaining = calculateRemainingTime(itemId, item.date)
  
  if (remaining.expired) {
    clearInterval(countdownTimers.value[itemId])
    delete countdownTimers.value[itemId]
    item.countdown = '已过期'
  } else {
    item.countdown = `${remaining.days}天 ${remaining.hours}小时 ${remaining.minutes}分 ${remaining.seconds}秒`
  }
}

// 获取购物记录
const fetchShopHistory = async () => {
  try {
    isLoading.value = true
    const userId = userManager.getUserId()
    shopItemService.getShopItemHistory(userId, (res) => {
      shopHistory.value = (res.data || []).map(item => {
        if (item.type === ITEM_TYPE.VIRTUAL && !item.isEffective && item.date) {
          const remaining = calculateRemainingTime(item.item_id, item.date)
          return {
            ...item,
            countdown: remaining.expired 
              ? '已过期' 
              : `${remaining.days}天 ${remaining.hours}小时 ${remaining.minutes}分 ${remaining.seconds}秒`
          }
        }
        return item
      })
      initCountdowns()
    })
  } catch (error) {
    errorMessage.value = '获取购物记录失败，请稍后重试'
    ElMessage.error('获取购物记录失败')
  } finally {
    isLoading.value = false
  }
}

// 使用虚拟卡
const useVirtualCard = (item) => {
  if (hasUsedSameCardToday.value(item.item_id)) {
    ElMessage.warning('同一种虚拟卡每天只能使用一次')
    return
  }

  ElMessageBox.confirm('确定要使用这张虚拟卡吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
    customClass: 'message-box-custom'
  }).then(() => {
    shopItemService.useVirtualCard(item.item_id, (res) => {
      if (res.code === 1000) {
        // 如果是分组卡片，减少数量或移除
        if (item.isGrouped) {
          if (item.count > 1) {
            item.count--
          } else {
            // 如果是最后一张，更新为已使用状态
            item.isEffective = 0
            item.isGrouped = false
          }
        } else {
          item.isEffective = 0
        }
        
        const validityItem = validityPeriod.find(v => v.item_id === item.item_id)
        const period = validityItem ? validityItem.period : 7
        
        const endDate = new Date()
        endDate.setDate(endDate.getDate() + period)
        item.date = endDate.toISOString()
        
        // 立即计算并显示剩余时间
        const remaining = calculateRemainingTime(item.item_id, item.date)
        item.countdown = remaining.expired 
          ? '已过期' 
          : `${remaining.days}天 ${remaining.hours}小时 ${remaining.minutes}分 ${remaining.seconds}秒`
        
        // 启动定时器
        countdownTimers.value[item.item_id] = setInterval(() => {
          updateCountdown(item.item_id, item.date)
        }, 1000)
        
        ElMessage({
          message: '虚拟卡使用成功',
          type: 'success',
          customClass: 'message-custom'
        })
        location.reload()
      } else {
        ElMessage.error(res.message || '使用虚拟卡失败')
      }
    })
  }).catch(() => {})
}

// 确认收货
const confirmReceipt = (item) => {
  ElMessageBox.confirm('确认已收到该商品吗?', '确认收货', {
    confirmButtonText: '确认收货',
    cancelButtonText: '取消',
    type: 'info',
    customClass: 'message-box-custom'
  }).then(() => {
    shopItemService.confirmReceipt(item.item_id, (res) => {
      if (res.code === 1000) {
        item.isEffective = 0
        ElMessage({
          message: '收货成功',
          type: 'success',
          customClass: 'message-custom'
        })
      } else {
        ElMessage.error(res.message || '收货失败')
      }
    })
  }).catch(() => {})
}

// 使用头像框
const useFrame = (item) => {
  ElMessageBox.confirm('确定要使用这个头像框吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    shopItemService.useFrame(item.item_id, (res) => {
      if (res.code === 1000) {
        shopHistory.value.forEach(shopItem => {
          if (shopItem.type === ITEM_TYPE.FRAME && shopItem.item_id !== item.item_id) {
            shopItem.isEffective = 1 // 设置为未使用
          }
        })
        item.isEffective = 0
        console.log(res)
        userManager.setUserFrameUrl(item.item_id)
        ElMessage.success('头像框使用成功')
      } else {
        ElMessage.error(res.message || '使用头像框失败')
      }
    })
  }).catch(() => {})
}

// 清理定时器
const clearAllTimers = () => {
  Object.values(countdownTimers.value).forEach(timer => {
    clearInterval(timer)
  })
  countdownTimers.value = {}
}

// 获取类型名称
const getTypeName = (type) => {
  switch(type) {
    case ITEM_TYPE.VIRTUAL: return '积分卡'
    case ITEM_TYPE.PHYSICAL: return '实体商品'
    case ITEM_TYPE.FRAME: return '头像框'
    default: return '未知类型'
  }
}
// 初始化加载数据
onMounted(() => {
  fetchShopHistory()
})

onUnmounted(() => {
  clearAllTimers()
})
</script>

<template>
  <div class="shop-history-container">
    <el-page-header class="page-header">
      <template #content>
        <span class="header-title">我的购物记录</span>
      </template>
    </el-page-header>

    <el-divider class="custom-divider" />

    <!-- 标签页 -->
    <el-tabs v-model="activeTab" class="type-tabs">
      <el-tab-pane label="虚拟卡" name="virtual"></el-tab-pane>
      <el-tab-pane label="实体商品" name="physical"></el-tab-pane>
      <el-tab-pane label="头像框" name="frame"></el-tab-pane>
    </el-tabs>

    <!-- 错误提示 -->
    <el-alert 
      v-if="errorMessage"
      :title="errorMessage"
      type="error"
      show-icon
      closable
      class="custom-alert"
    />

    <!-- 加载状态 -->
    <div v-if="isLoading" class="skeleton-container">
      <el-skeleton 
        v-for="i in 4" 
        :key="i" 
        animated 
        class="custom-skeleton"
      >
        <template #template>
          <el-skeleton-item variant="image" class="skeleton-image" />
          <div class="skeleton-content">
            <el-skeleton-item variant="h3" class="skeleton-title" />
            <el-skeleton-item variant="text" class="skeleton-text" />
            <el-skeleton-item variant="text" class="skeleton-text" />
          </div>
        </template>
      </el-skeleton>
    </div>

    <!-- 空状态 -->
    <el-empty 
      v-else-if="filteredHistory.length === 0"
      :description="`暂无${getTypeName(ITEM_TYPE[activeTab.toUpperCase()])}记录`"
      :image-size="200"
      class="custom-empty"
    >
      <el-button type="primary" @click="$router.push('/shop')">
        去商城逛逛
      </el-button>
    </el-empty>

    <!-- 购物记录列表 -->
    <el-row :gutter="20" v-else class="card-row">
      <el-col 
        v-for="(item, index) in filteredHistory" 
        :key="index" 
        :xs="24" :sm="12" :md="8" :lg="6"
      >
        <el-card 
          shadow="hover" 
          class="custom-card"
          :body-style="{ padding: '0', display: 'flex', flexDirection: 'column', height: '100%' }"
        >
          <!-- 商品图片 -->
          <div class="card-image-container">
            <el-image 
              v-if="item.imageUrl" 
              :src="imagePath.getServerImagePath(item.imageUrl)" 
              :alt="item.title"
              fit="cover"
              class="card-image"
              :preview-src-list="[imagePath.getServerImagePath(item.imageUrl)]"
            >
              <template #error>
                <div class="image-error">
                  <el-icon :size="40"><Picture /></el-icon>
                  <span>图片加载失败</span>
                </div>
              </template>
              <template #placeholder>
                <div class="image-loading">
                  <el-icon class="is-loading" :size="40"><Loading /></el-icon>
                </div>
              </template>
            </el-image>
            <div v-else class="image-placeholder">
              {{ getTypeName(item.type) }}
            </div>
            
            <!-- 商品类型标签 -->
            <el-tag 
              class="type-tag"
              :type="item.type === ITEM_TYPE.VIRTUAL ? 'success' : item.type === ITEM_TYPE.PHYSICAL ? 'primary' : 'warning'"
              effect="dark"
              round
            >
              {{ getTypeName(item.type) }}
            </el-tag>
          </div>
          
          <!-- 商品内容 -->
          <div class="card-content">
            <div class="content-header">
      <h3 class="item-title">{{ item.title }}</h3>
      
      <!-- 显示未使用卡片的数量 -->
      <div v-if="item.isEffective && item.isGrouped" class="item-count">
        <el-tag type="info" effect="plain" round>
          {{ item.count }}张可用
        </el-tag>
      </div>
      
      <!-- 商品状态 -->
      <el-tag 
        class="status-tag"
        :type="
          item.type === ITEM_TYPE.VIRTUAL 
            ? (item.isEffective ? 'warning' : 'info') 
            : item.type === ITEM_TYPE.PHYSICAL
              ? (item.isEffective ? 'success' : 'danger')
              : (item.isEffective ? 'warning' : 'success')
        "
        effect="light"
        round
      >
        <span v-if="item.type === ITEM_TYPE.VIRTUAL">
          {{ item.isEffective ? '未使用' : '已使用' }}
        </span>
        <span v-else-if="item.type === ITEM_TYPE.PHYSICAL">
          {{ item.isEffective ? '已收货' : '待收货' }}
        </span>
        <span v-else>
          {{ item.isEffective ? '未使用' : '已使用' }}
        </span>
      </el-tag>
            </div>

            <p class="item-desc">{{ item.description }}</p>
            
            <!-- 倒计时显示 -->
            <div v-if="item.type === ITEM_TYPE.VIRTUAL && !item.isEffective" class="countdown-container">
             <el-tag type="info" effect="plain" class="countdown-tag">
            <el-icon><Clock /></el-icon>
            <span class="countdown-text">生效剩余: {{ item.countdown }}</span>
            </el-tag>
            </div>

            <!-- 操作按钮 -->
            <div class="card-actions">
              <!-- 虚拟卡操作 -->
              <template v-if="item.type === ITEM_TYPE.VIRTUAL">
                <el-button 
                  v-if="item.isEffective"
                  type="primary" 
                  size="small"
                  @click="useVirtualCard(item)"
                  class="action-btn"
                  round
                >
                  <el-icon><Ticket /></el-icon>
                  <span>立即使用</span>
                </el-button>
                
                <el-button 
                  v-else
                  type="info" 
                  size="small"
                  disabled
                  class="action-btn"
                  round
                >
                  <el-icon><Checked /></el-icon>
                  <span>已使用</span>
                </el-button>
              </template>
              
              <!-- 实体商品操作 -->
              <template v-else-if="item.type === ITEM_TYPE.PHYSICAL">
                <el-button 
                  v-if="item.isEffective"
                  type="success" 
                  size="small"
                  @click="confirmReceipt(item)"
                  class="action-btn"
                  round
                >
                  <el-icon><CircleCheck /></el-icon>
                  <span>确认收货</span>
                </el-button>
                
                <el-button 
                  v-else
                  type="success" 
                  size="small"
                  disabled
                  class="action-btn"
                  round
                >
                  <el-icon><CircleCheckFilled /></el-icon>
                  <span>已收货</span>
                </el-button>
              </template>
              
              <!-- 头像框操作 -->
              <template v-else-if="item.type === ITEM_TYPE.FRAME">
                <el-button 
                  v-if="item.isEffective"
                  type="warning" 
                  size="small"
                  @click="useFrame(item)"
                  class="action-btn"
                  round
                >
                  <el-icon><Checked /></el-icon>
                  <span>立即使用</span>
                </el-button>
                
                <el-button 
                  v-else
                  type="success" 
                  size="small"
                  disabled
                  class="action-btn"
                  round
                >
                  <el-icon><CircleCheckFilled /></el-icon>
                  <span>已使用</span>
                </el-button>
              </template>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<style scoped>
.shop-history-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

/* 头部样式 */
.page-header {
  margin-bottom: 10px;
}
.header-title {
  font-size: 1.5rem;
  font-weight: 500;
  color: var(--el-color-primary);
}
.custom-divider {
  margin: 10px 0 20px;
}

/* 标签页样式 */
.type-tabs {
  margin-bottom: 20px;
}

/* 错误提示 */
.custom-alert {
  margin-bottom: 20px;
  border-radius: 8px;
}

/* 加载状态 */
.skeleton-container {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
  gap: 20px;
}
.custom-skeleton {
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}
.skeleton-image {
  width: 100%;
  height: 180px;
}
.skeleton-content {
  padding: 15px;
}
.skeleton-title {
  width: 80%;
  height: 24px;
  margin-bottom: 15px;
}
.skeleton-text {
  width: 100%;
  height: 16px;
  margin-bottom: 10px;
}

/* 空状态 */
.custom-empty {
  padding: 40px 0;
  background: transparent;
}
.custom-empty :deep(.el-empty__description) {
  margin-top: 10px;
  color: var(--el-text-color-secondary);
}

/* 卡片列表 */
.card-row {
  margin-top: 10px;
}
/* 卡片样式 */
.custom-card {
  border-radius: 12px;
  margin-bottom: 20px;
  height: 100%;
  transition: transform 0.3s, box-shadow 0.3s;
  border: none;
}
.custom-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 10px 20px rgba(0, 0, 0, 0.12);
}
.item-count {
  margin-right: 8px;
}

/* 图片区域 */
.card-image-container {
  position: relative;
  height: 180px;
  overflow: hidden;
}
.card-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.5s;
}
.custom-card:hover .card-image {
  transform: scale(1.05);
}
.image-error, .image-loading {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  color: var(--el-text-color-secondary);
  background-color: var(--el-fill-color-light);
}
.image-placeholder {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  color: var(--el-text-color-secondary);
  font-size: 16px;
  font-weight: 500;
}

/* 类型标签 */
.type-tag {
  position: absolute;
  top: 10px;
  right: 10px;
  font-weight: bold;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

/* 卡片内容 */
.card-content {
  padding: 16px;
  flex: 1;
  display: flex;
  flex-direction: column;
}
.content-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 12px;
}
.item-title {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
  color: var(--el-text-color-primary);
  flex: 1;
  line-height: 1.4;
}
.status-tag {
  margin-left: 8px;
  flex-shrink: 0;
}
.item-desc {
  margin: 0 0 16px;
  font-size: 14px;
  color: var(--el-text-color-secondary);
  line-height: 1.5;
  flex: 1;
  display: -webkit-box;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

/* 倒计时容器 */
.countdown-container {
  margin: 10px 0;
  display: flex;
  justify-content: center;
}
.countdown-tag {
  padding: 6px 12px;
  font-size: 13px;
}
.countdown-text {
  margin-left: 6px;
  font-weight: 500;
}

/* 操作按钮 */
.card-actions {
  margin-top: auto;
  display: flex;
  justify-content: flex-end;
}
.action-btn {
  margin-left: 8px;
}
.action-btn span {
  margin-left: 4px;
}

/* 全局消息框样式 */
.message-box-custom {
  border-radius: 12px;
}
.message-custom {
  border-radius: 8px;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .card-row {
    margin-left: 0;
    margin-right: 0;
  }
  .card-content {
    padding: 12px;
  }
}
</style>